package main

var maxAbs uint64 = 1<<31 - 1
var minAbs uint64 = 1 << 31

func toNum(c uint8) (int, bool) {
	n := int(c) - '0'
	if n < 0 || n > 9 {
		return 0, false
	}
	return n, true
}

func myAtoi(s string) int {
	i := 0
	for ; i < len(s) && s[i] == ' '; i++ {
	}
	if i == len(s) {
		return 0
	}
	sign := 1
	if s[i] == '+' {
		sign = 1
		i++
	} else if s[i] == '-' {
		sign = -1
		i++
	}
	var ans uint64 = 0
	for ; i < len(s); i++ {
		n, ok := toNum(s[i])
		if !ok {
			break
		}
		ans = ans*10 + uint64(n)
		if sign > 0 && ans > maxAbs {
			return int(maxAbs)
		} else if sign < 0 && ans > minAbs {
			return -int(minAbs)
		}
	}
	return int(ans) * sign
}

func main() {
	println(myAtoi(""))
	println(myAtoi(" "))
	println(myAtoi("42"))
	println(myAtoi("42a"))
	println(myAtoi("a42"))
	println(myAtoi("+42"))
	println(myAtoi("-42"))
	println(myAtoi("2147483647"))
	println(myAtoi("2147483648"))
	println(myAtoi("-2147483648"))
	println(myAtoi("-91283472332"))
}
